from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken
import json
import random
import logging
from . import models
from rest_framework_simplejwt.views import TokenObtainPairView
from django.utils import timezone
import datetime
from django.contrib.auth.hashers import make_password, check_password
from rest_framework import views
from django.forms.models import model_to_dict
from users.models import Users
from flight.models import Itinerary
from django.core.cache import cache
from algorithm.updateData import update
from algorithm.encode import myEncode
from algorithm.DecisionTreeRegression import MyTreeRegression
from algorithm.predict import insertPredict

@csrf_exempt
def add_personal(request):
    global message
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            username = data['userId']
            email = data['email']
            password = '123456'

            # 检查用户是否已经存在
            user = Users.objects.filter(username=username).first()
            print(user)
            if user:
                message = '用户已存在'
            else:
                print(username)
                userNew = Users.objects.create(
                    username=username,
                    password=make_password(password),  # 加密密码
                    email=email
                )
                userNew.save()

                # 返回成功响应
                return JsonResponse({
                    'status': 200,
                    'message': '用户创建成功',
                    'data': {
                        'username': userNew.username,
                        'email': userNew.email
                    }
                })

        except Exception as e:
            return JsonResponse({'message': message, 'error': str(e)}, status=500)

    return JsonResponse({'message': '无效请求'}, status=400)


@csrf_exempt
def get_personal(request):
    if request.method == 'GET':
        try:
            all_users = Users.objects.all()
            data = []
            for user in all_users:
                user_data = {
                    "userId": user.username,
                    "email": user.email
                }
                data.append(user_data)

            # 打印整个用户数据
            print(data)
            return JsonResponse({"data": data}, status=200)
        except Exception as e:
            print(f"Error: {str(e)}")
            return JsonResponse({"error": "内部服务器错误", "message": str(e)}, status=500)
    return JsonResponse({"message": "无效请求"}, status=400)

@csrf_exempt
def save_personal(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            username = data.get('userId')
            email = data.get('email')
            oldUserId = data.get('oldUserId')

            # 检查必要字段
            if not username or not email or not oldUserId:
                return JsonResponse({'message': '缺少必要字段'}, status=400)

            try:
                # 获取旧用户信息
                user = Users.objects.get(username=oldUserId)

                # 更新用户信息
                user.username = username
                user.email = email
                user.save()

                return JsonResponse({
                    'status': 200,
                    'message': '用户信息更新成功',
                    'data': {
                        'username': user.username,
                        'email': user.email
                    }
                })
            except Users.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=404)

        except json.JSONDecodeError:
            return JsonResponse({'message': '请求格式错误'}, status=400)
        except Exception as e:
            return JsonResponse({'message': '内部服务器错误', 'error': str(e)}, status=500)

    return JsonResponse({'message': '无效请求'}, status=400)

@csrf_exempt
def delete_personal(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            username = data.get('userId')
            email = data.get('email')

            # 检查必要字段
            if not username or not email:
                return JsonResponse({'message': '缺少必要字段'}, status=400)

            try:
                # 获取并删除匹配的用户
                user = Users.objects.get(username=username, email=email)
                user.delete()

                return JsonResponse({
                    'status': 200,
                    'message': '用户删除成功'
                })
            except Users.DoesNotExist:
                return JsonResponse({'message': '用户不存在'}, status=404)

        except json.JSONDecodeError:
            return JsonResponse({'message': '请求格式错误'}, status=400)
        except Exception as e:
            return JsonResponse({'message': '内部服务器错误', 'error': str(e)}, status=500)

    return JsonResponse({'message': '无效请求'}, status=400)

@csrf_exempt
def data_manageFlight(request):
    if request.method == 'GET':
        try:
            cache_key = 'all_itineraries'
            cached_data = cache.get(cache_key)

            if cached_data:
                data = cached_data
            else:
                all_itineraries = Itinerary.objects.all()
                data = []
                for itinerary in all_itineraries:
                    airline = itinerary.airline
                    flight_no = itinerary.flight_no

                    # 计算航程时间（这里假设航程在同一天，如果跨天需要额外处理）
                    if itinerary.departure_time and itinerary.arrival_time:
                        duration_hours = itinerary.arrival_time.hour - itinerary.departure_time.hour
                        duration_minutes = itinerary.arrival_time.minute - itinerary.departure_time.minute
                        if duration_minutes < 0:
                            duration_hours -= 1
                            duration_minutes += 60
                        duration = f"{duration_hours}小时{duration_minutes}分钟"
                    else:
                        duration = "未知"

                    flight_data = {
                        "airline": airline,
                        "airlineNum": flight_no,
                        "duration": duration,
                        "price": itinerary.price,
                        "route": f"{itinerary.departure_city}-{itinerary.arrival_city}",
                        "startDate": itinerary.departure_date.strftime('%m月%d日') if itinerary.departure_date else "未知",
                        "uid": itinerary.itinerary_id
                    }
                    data.append(flight_data)

                # 将数据存储到缓存中，设置过期时间为1小时（3600秒）
                cache.set(cache_key, data, timeout=3600)

            return JsonResponse({"status": 200, "data": data}, status=200)
        except Exception as e:
            print(f"Error: {str(e)}")
            return JsonResponse({"error": "内部服务器错误", "message": str(e)}, status=500)
    return JsonResponse({"message": "无效请求"}, status=400)
@csrf_exempt
def save_manageFlight(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))

            # 获取前端传入的数据
            airline = data.get('airline')
            start_date = data.get('startDate')
            flight_no = data.get('airlineNum')
            old_uid = data.get('olduid')
            price = data.get('price')
            route = data.get('route')
            uid = data.get('uid')

            # 检查必要字段
            if not uid:
                return JsonResponse({'message': '缺少必要字段: uid'}, status=400)
                # 转换日期格式
            try:
                departure_date = datetime.datetime.strptime(start_date, '%m月%d日').replace(
                    year=datetime.datetime.now().year).date()
            except ValueError:
                return JsonResponse({'message': '日期格式错误，应为 "MM月DD日"'}, status=400)
            try:
                # 获取并更新航程信息
                itinerary = Itinerary.objects.get(itinerary_id=uid)

                # 分离出发和到达城市
                departure_city, arrival_city = route.split('-')

                # 更新航程信息
                itinerary.airline = airline
                itinerary.flight_no = flight_no
                itinerary.departure_city = departure_city
                itinerary.arrival_city = arrival_city
                itinerary.departure_date = departure_date
                itinerary.price = price

                itinerary.save()

                return JsonResponse({'status': 200, 'message': '航程信息更新成功'})
            except Itinerary.DoesNotExist:
                return JsonResponse({'message': '航程不存在'}, status=404)

        except json.JSONDecodeError:
            return JsonResponse({'message': '请求格式错误'}, status=400)
        except Exception as e:
            return JsonResponse({'message': '内部服务器错误', 'error': str(e)}, status=500)
    return JsonResponse({'message': '无效请求'}, status=400)
@csrf_exempt
def add_manageFlight(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))

            # 获取前端传入的数据
            flight_no = data.get('flight_no')
            airline = data.get('airline')
            departure_city = data.get('departure_city')
            departure_airport = data.get('departure_airport')
            arrival_city = data.get('arrival_city')
            arrival_airport = data.get('arrival_airport')
            departure_time = data.get('departure_time')
            departure_date = data.get('departure_date')
            arrival_date = data.get('arrival_date')
            arrival_time = data.get('arrival_time')
            price = data.get('price')
            # 检查必要字段
            if not all([flight_no, airline, departure_city, arrival_city, departure_date, price]):
                return JsonResponse({'message': '缺少必要字段'}, status=400)

            # 创建新的航程
            itinerary = Itinerary.objects.create(
                flight_no=flight_no,
                airline=airline,
                departure_city=departure_city,
                departure_airport=departure_airport,
                arrival_city=arrival_city,
                arrival_airport=arrival_airport,
                departure_time=departure_time,
                departure_date=departure_date,
                arrival_date=arrival_date,
                arrival_time=arrival_time,
                price=price
            )

            return JsonResponse({'status': 200, 'message': '航程添加成功', 'uid': itinerary.itinerary_id})
        except json.JSONDecodeError:
            return JsonResponse({'message': '请求格式错误'}, status=400)
        except Exception as e:
            return JsonResponse({'message': '内部服务器错误', 'error': str(e)}, status=500)
    return JsonResponse({'message': '无效请求'}, status=400)

@csrf_exempt
def delete_manageFlight(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body.decode('utf-8'))
            itinerary_id = data.get('uid')
            print(f"Received itinerary_id: {itinerary_id}")

            if not itinerary_id:
                return JsonResponse({'message': '缺少必要字段: uid'}, status=400)

            # 查找并删除航程
            itinerary = Itinerary.objects.get(itinerary_id=itinerary_id)
            print(f"Found itinerary: {itinerary}")
            itinerary.delete()

            print(f"Deleted itinerary with id: {itinerary_id}")
            return JsonResponse({'status': 200, 'message': '航程删除成功'})

        except Itinerary.DoesNotExist:
            return JsonResponse({'message': '航程不存在'}, status=404)

        except json.JSONDecodeError:
            return JsonResponse({'message': '请求格式错误'}, status=400)

        except Exception as e:
            print(f"Error: {str(e)}")
            return JsonResponse({'message': '内部服务器错误', 'error': str(e)}, status=500)

    return JsonResponse({'message': '无效请求'}, status=400)

@csrf_exempt
def update_data(request):
    if request.method == 'GET':
        try:
            print("update.......")
            update()
            myEncode()
            MyTreeRegression()
            insertPredict()
            return JsonResponse({"message": "success"}, status=200)
        except Exception as e:
            print(f"Error: {str(e)}")
            return JsonResponse({"error": "内部服务器错误", "message": str(e)}, status=500)
    return JsonResponse({"message": "无效请求"}, status=400)